package com.demo.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.demo.entity.User2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangfengchen
 */
@RestController
@RequestMapping
public class TestHutoolExcel {

  @GetMapping("/export")
  public void exports(HttpServletResponse response) {

    //模拟数据
    List<User2> list = new ArrayList<User2>();
    list.add(new User2("zhangsan", 12, new Date()));
    list.add(new User2("zhangsan1", 18, new Date()));
    list.add(new User2("zhangsan2", 23, new Date()));
    list.add(new User2("zhangsan3", 25, new Date()));
    list.add(new User2("zhangsan4", 30, new Date()));
    list.add(new User2("zhangsan5", 36, new Date()));

    //通过工具类创建writer，默认创建xls格式
    ExcelWriter writer = ExcelUtil.getWriter();

    //自定义标题名
    writer.addHeaderAlias("name", "姓名");
    writer.addHeaderAlias("age", "年龄");
    writer.addHeaderAlias("birthday", "生日");

    // 合并单元格后的标题行，使用默认标题样式
    writer.merge(2, "申请人员信息");

    //一次性写出内容，使用默认样式，强制输出标题
    //Iterable<?>  data
    writer.write(list, true);

    //response为HttpServeltReponse对象
    response.setContentType("application/vnd.ms-excel;charset=utf-8");

    //弹出下载对话框的文件名，不能为中文，中文请自行编码

    String name = "申请学院";
    try {
      name = URLEncoder.encode(name, StandardCharsets.UTF_8.toString());
      response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    ServletOutputStream out = null;
    try {
      out = response.getOutputStream();
      writer.flush(out, true);

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //关闭writer,释放内存
      writer.close();
    }
    IoUtil.close(out);

  }

}
